package org.netty.client.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.log4j.Logger;
import org.netty.pojo.User;
import org.netty.protocol.Protocol;
import org.netty.protocol.file.Constants;
import org.netty.protocol.file.FileBurstData;
import org.netty.protocol.file.FileBurstInstruct;
import org.netty.protocol.file.FileTransferProtocol;
import org.netty.utils.ProtocolUtils;
import org.netty.utils.file.FileUtil;
import org.netty.utils.file.MsgUtil;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

public class ClientHandler extends ChannelInboundHandlerAdapter {
    private final Logger logger = Logger.getLogger(this.getClass());

    //连接成功后发送消息测试
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        User user = new User();
        user.setBirthday(new Date());
        user.setUID(UUID.randomUUID().toString());
        user.setName("冉鹏峰");
        user.setAge(24);
        //        传单一实体
        ctx.write(ProtocolUtils.prtclInstance(user));
        ctx.flush();

        Map<String, Object> map = new HashMap<>();
        map.put("数据一", user);
        List<Map<String,Object>> users = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            users.add(map);
        }
        Protocol protocol = ProtocolUtils.prtclInstance(map);
//        传map
        ctx.write(protocol);//由于设置了编码器，这里直接传入自定义的对象
        ctx.flush();
//        传list
        ctx.write(ProtocolUtils.prtclInstance(users));
        ctx.flush();


//        文件
        File file = new File("D:\\download\\netty_TCP-master.zip");
        FileTransferProtocol fileTransferProtocol = MsgUtil.buildRequestTransferFile(file.getAbsolutePath(), file.getName(), file.length());
        //发送信息；请求传输文件
        ctx.writeAndFlush(ProtocolUtils.prtclInstance(fileTransferProtocol));

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //数据格式验证
        if ((msg instanceof FileTransferProtocol)) {

            FileTransferProtocol fileTransferProtocol = (FileTransferProtocol) msg;
            //0传输文件'请求'、1文件传输'指令'、2文件传输'数据'
            switch (fileTransferProtocol.getTransferType()) {
                case 1:
                    FileBurstInstruct fileBurstInstruct = (FileBurstInstruct) fileTransferProtocol.getTransferObj();
                    //Constants.FileStatus ｛0开始、1中间、2结尾、3完成｝
                    if (Constants.FileStatus.COMPLETE == fileBurstInstruct.getStatus()) {
                        ctx.flush();
                        System.out.println("发送完成");
//                        ctx.close();
//                        System.exit(-1);
                        return;
                    }
                    FileBurstData fileBurstData = FileUtil.readFile(fileBurstInstruct.getClientFileUrl(), fileBurstInstruct.getReadPosition());
                    ctx.writeAndFlush(ProtocolUtils.prtclInstance(MsgUtil.buildTransferData(fileBurstData)));
                    logger.debug(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " 客户端传输文件信息。 FILE：" + fileBurstData.getFileName() + " SIZE(byte)：" + (fileBurstData.getEndPos() - fileBurstData.getBeginPos()));
                    break;
                default:
                    break;
            }
        }
    }

//    public byte[] getBytes(File file) {
//        LineIterator it = null;
//        try {
//            it = FileUtils.lineIterator(file, "UTF-8");
//            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//            while (it.hasNext()) {
//                String line = it.nextLine();
//                outputStream.write(line.getBytes(StandardCharsets.UTF_8));
//            }
//            return outputStream.toByteArray();
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            LineIterator.closeQuietly(it);
//        }
//        return null;
//    }
}
